<?php

namespace plugins\user\backend\controller;

use app\controller\backend\BaseController;
use plugins\user\model\UserGrade;
use plugins\user\validate\UserGradeValidate;
use think\exception\ValidateException;

class UserGradeController extends BaseController
{

    public function index()
    {
        $param = $this->request->only([
            'limit' => 10,
        ]);

        $where = [];

        $userModel = new UserGrade();
        $list = $userModel->getList($where, ['icon'], $param['limit'], 'sort asc');

        return json(pageReturn($list));
    }

    public function add()
    {
        $param = $this->request->post([
            'title' => '',
            'icon' => '',
            'min_score' => '',
            'max_score' => '',
            'sort' => 0,
        ]);
        try {
            validate(UserGradeValidate::class)->scene('save')->check($param);
        } catch (ValidateException $e) {
            return jsonReturn(-1, $e->getError());
        }

        $param['seller_id'] = $this->admin['seller_id'];

        $userModel = new UserGrade();
        $res = $userModel->add($param);

        return json($res);
    }

    public function edit()
    {
        $param = $this->request->post([
            'id' => 0,
            'title' => '',
            'icon' => '',
            'min_score' => '',
            'max_score' => '',
            'sort' => 0,
        ]);
        try {
            validate(UserGradeValidate::class)->scene('update')->check($param);
        } catch (ValidateException $e) {
            return jsonReturn(-1, $e->getError());
        }

        $userModel = new UserGrade();
        $res = $userModel->edit(['id' => $param['id']], $param);

        return json($res);
    }

    public function del()
    {
        $param = $this->request->post([
            'id' => 0,
        ]);
        try {
            validate(UserGradeValidate::class)->scene('del')->check($param);
        } catch (ValidateException $e) {
            return jsonReturn(-1, $e->getError());
        }

        $userModel = new UserGrade();
        $res = $userModel->where(['id' => $param['id']])->delete();
        if ($res === false) {
            return jsonReturn(-1, lang('删除失败'));
        }
        return jsonReturn(0, lang('删除成功'));
    }

}
